package com.bthdung.studios.lesson12;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;

public class GLES20SurfaceView extends GLSurfaceView
{

	MyRenderer renderer;
	ScaleGestureDetector scaleDetector;

	public GLES20SurfaceView(Context context)
	{
		super(context);
		setEGLContextClientVersion(2);

		renderer = new MyRenderer(context);
		setRenderer(renderer);

		scaleDetector = new ScaleGestureDetector(context, new liste());
	}

	float lastX = 0;
	boolean pinch = false;

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		if (event.getPointerCount() == 1)
		{
			if (pinch)
			{
				pinch = false;
				lastX = event.getX();
			}
			else if (event.getAction() == MotionEvent.ACTION_DOWN)
			{
				lastX = event.getX();
			}
			else if (event.getAction() == MotionEvent.ACTION_MOVE)
			{
				float x = event.getX();
				renderer.vel += (x - lastX) / 100f;

				lastX = x;
			}
		}
		else
		{
			pinch = true;
		}

		scaleDetector.onTouchEvent(event);

		return true;
	}

	class liste extends ScaleGestureDetector.SimpleOnScaleGestureListener
	{
		@Override
		public boolean onScale(ScaleGestureDetector detector)
		{
			float span1 = detector.getPreviousSpan();
			float span2 = detector.getCurrentSpan();
			float span = detector.getScaleFactor() / 100f;

			if (span1 < span2) span *= -1f;

			renderer.zoom(span);
			return false;
		}

		@Override
		public void onScaleEnd(ScaleGestureDetector detector)
		{
			super.onScaleEnd(detector);
		}
	}

}
